const { Add, Update, QueryById, Query, QueryOne, Exec } = require('../db/dbhelper');
const { init, format } = require('../models/msgsubscribe');
const logger = require('../libs/log').logger;
const { wechat } = require('../../server_config.json')

//新增
const msgsubscribeAdd = function (doc) {
  return Add('hzz_msgsubscribes', init(doc));
}

//已发送，变更可继续发送状态
const msgsubscribeUpdate = async function (pcode, msgtmpid) {
  logger.info(`------msgsubscribeUpdate--------,`,pcode, msgtmpid);
  let msg = await QueryOne('hzz_msgsubscribes', { pcode: pcode, msgtmpid: msgtmpid });
  if (msg) {
    // 已订阅一次性消息的，修改可发送状态为否
    // if(msg.status===1){
    //   if(msg.state===1){
    logger.info(`消息发送成功，修改用户code【${pcode}】订阅一次性消息【${msgtmpid}】，重置消息订阅状态！`);
    
    Update('hzz_msgsubscribes', format({id: msg.id, isusing: 0}));
    //   }
    // }
  }
}

//查询用户是否弹出订阅消息
const msgsubscribeIsRead = async function (pcode) {
  let msg = await Query('hzz_msgsubscribes', { pcode: pcode, isusing: 1 });
  if (msg && msg.length == 3) {
    return false;
  } else {
    return true;
  }
}

// 更新
const msgsubscribeEdit = async function (doc) {
  logger.info('---------msgsubscribeEdit---', doc)
  let data = await QueryOne('hzz_msgsubscribes', { pcode: doc.pcode, msgtmpid: doc.msgtmpid });
  if (data) {
    doc.id = data.id;
    await Update('hzz_msgsubscribes', format(doc));
  } else {
    await Add('hzz_msgsubscribes', init(doc));
  }
}

module.exports = {
  msgsubscribeAdd,
  msgsubscribeUpdate,
  msgsubscribeIsRead,
  msgsubscribeEdit
}